package com.sub.commons.filter;

import com.alibaba.fastjson.JSON;
import com.sub.utils.BaseContext;
//import com.sub.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
//@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    //Spring的路径匹配器
    public static final AntPathMatcher PATH_MATCHER=new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        String uri = request.getRequestURI();
        log.info("拦截到的请求：{}",uri);
        boolean result = iPass(uri);
        if (result){
            filterChain.doFilter(request,servletResponse);
            log.info("本次请求{}不需要处理",uri);
            return;
        }
        //判断用户是否已登录
        Long id = (Long) request.getSession().getAttribute("employee");
        if (id!=null){
            //已登录过
            BaseContext.setId(id);
            log.info("用户已登录，用户id为：{}",request.getSession().getAttribute("employee"));
            filterChain.doFilter(request,servletResponse);
            return;
        }
        //判断前台系统用户登录状态，如果已登录，则直接放行
        if(request.getSession().getAttribute("user") != null){
            log.info("用户已登录，用户id为：{}",request.getSession().getAttribute("user"));
            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContext.setId(userId);
            //BaseContext.setCurrentId(userId);
            filterChain.doFilter(request,servletResponse);
            return;
        }
        //既不放行匹配路径，又没有登录，则不放行，并给前端设置响应消息：NOTLOGIN
        log.info("用户未登录");
        HttpServletResponse response= (HttpServletResponse) servletResponse;
        //response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }

    /**
     * 路径匹配器
     * @param uri URI
     * @return Boolean
     */
    public boolean iPass(String uri){
        String[] uris=new String[]{"/backend/**","/front/**","/employee/login","/user/sendMsg","/user/login","/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"};
        for (String s : uris) {
            boolean match = PATH_MATCHER.match(s, uri);
            if (match){
                return true;
            }
        }
        return false;
    }
}
